// projects/dynamic-forms/src/lib/dynamic-segment-configuration.component.ts
import { Component, Input, Output, EventEmitter, ViewChild, ViewContainerRef, OnChanges, SimpleChanges, AfterViewInit } from '@angular/core';
import { UniqueCodeConfigService } from './unique-code-config.service';

@Component({
  selector: 'dynamic-segment-configuration',
  template: `<ng-container #container></ng-container>`
})
export class DynamicSegmentConfigurationComponent implements OnChanges, AfterViewInit {
  @Input() type: string;
  @Input() configuration: string;
  @Output() configurationChange = new EventEmitter<string>();
  @Output() validityChanged = new EventEmitter<boolean>();

  @ViewChild('container', { read: ViewContainerRef, static: true }) container: ViewContainerRef;
  
  private componentRef: any;
  private pendingLoad = false;

  constructor(
    private uniqueCodeConfigService: UniqueCodeConfigService
  ) {}

  ngAfterViewInit() {
    if (this.pendingLoad) {
      this.loadComponent();
      this.pendingLoad = false;
    }
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes['type'] && this.type) {
      if (this.container) {
        this.loadComponent();
      } else {
        this.pendingLoad = true;
      }
    }
  }

  private loadComponent() {
    if (this.componentRef) {
      this.componentRef.destroy();
      this.componentRef = null;
    }

    const component = this.uniqueCodeConfigService.getSegmentComponent(this.type);
    if (!component) return;

    this.container.clear();
    this.componentRef = this.container.createComponent(component);

    // 设置初始配置
    let config = {};
    try {
      config = this.configuration ? JSON.parse(this.configuration) : {};
    } catch (e) {
      console.error('Invalid configuration JSON:', e);
    }
    
    this.componentRef.instance.formData = config;

    // 监听配置变更
    this.componentRef.instance.configurationChanged.subscribe(value => {
      this.configurationChange.emit(JSON.stringify(value));
    });

    // 监听验证状态变更
    this.componentRef.instance.validityChanged.subscribe(isValid => {
      this.validityChanged.emit(isValid);
    });

    // 确保变更检测
    this.componentRef.changeDetectorRef.detectChanges();
  }

  ngOnDestroy() {
    if (this.componentRef) {
      this.componentRef.destroy();
      this.componentRef = null;
    }
  }
}



